package com.qf.service.impl;

import com.qf.Dao.UserRepository;
import com.qf.pojo.BaseResp;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.utils.MD5jiami;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserRepository userRepository;

    @Override
    public BaseResp login(User user) {
        System.out.println(user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getName(),user.getPassword());
        try {
            subject.login(usernamePasswordToken);
        } catch (AuthenticationException e) {
            System.out.println(e.getMessage());
        }
        BaseResp baseResp = new BaseResp();
        if(subject.isAuthenticated()){
            baseResp.setCode(200);
            baseResp.setMgs("登陆成功");
        }else{
            baseResp.setCode(201);
            baseResp.setMgs("用户名或密码错误");
        }
        return baseResp;
      }

    @Override
    public BaseResp add(User user) {
        BaseResp baseResp = new BaseResp();
        user.setPassword(MD5jiami.jiami(user.getPassword()));
        if(user.getId()!=null){
            userRepository.saveAndFlush(user);
            baseResp.setCode(200);
            baseResp.setMgs("修改成功");
        }else {
            userRepository.saveAndFlush(user);
            baseResp.setCode(200);
            baseResp.setMgs("新增成功");
        }
        return baseResp;
    }

    @Override
    public BaseResp del(Integer id) {
        BaseResp baseResp = new BaseResp();
        userRepository.deleteById(id);
        baseResp.setCode(200);
        baseResp.setMgs("删除成功");
        return baseResp;
    }

    @Override
    public BaseResp findAll(Integer page, Integer size) {
        BaseResp baseResp = new BaseResp();
        Pageable pageRequest = PageRequest.of(page - 1, size);
        Page<User> users = userRepository.findAll(pageRequest);
        baseResp.setCode(200);
        baseResp.setData(users.getContent());
        baseResp.setTotal(users.getTotalElements());
        return baseResp;
    }

}
